package com.imist.nettybasic4.server.handler;

import com.imist.nettybasic4.protocol.request.LoginRequestPacket;
import com.imist.nettybasic4.protocol.response.LoginResponsePacket;
import com.imist.nettybasic4.session.Session;
import com.imist.nettybasic4.utils.SessionUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

// 1. 加上注解，表明该handler是可以和多个channel共享的
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    //2. 构造单例
    public static final LoginRequestHandler  INSTANCE = new LoginRequestHandler();

    protected LoginRequestHandler() {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket packet) throws Exception {
            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            loginResponsePacket.setVersion(packet.getVersion());
            loginResponsePacket.setUserName(packet.getUsername());
            //登陆校验
            if (valid(packet)){
                //校验成功
                loginResponsePacket.setSuccess(true);
                String userId = randomUserId();
                loginResponsePacket.setUserId(userId);
                System.out.println("["+loginResponsePacket.getUserName()+"]"+"登陆成功");
                //将当前的用户会话信息绑定到当前的连接对象
                SessionUtils.bindSession(new Session(userId,packet.getUsername()),ctx.channel());
            }else {
                //校验失败
                loginResponsePacket.setSuccess(false);
                loginResponsePacket.setReason("账号密码校验失败...");
                System.out.println("登录失败");
            }
            //登录响应
            ctx.writeAndFlush(loginResponsePacket);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //用户断线之后取消绑定
        SessionUtils.unBindSession(ctx.channel());
    }

    private static String randomUserId() {
        return UUID.randomUUID().toString().split("-")[0];
    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        return true;
    }
}
